<template>
  <div class="tableRow">
    <el-row class="select-list" v-permission="'tool:gen:query'">
      <el-form :inline="true" ref="selectForm" :model="selectFormModel" :label-position="'right'"
               label-width="80px" size="mini" @submit.native.prevent>
        <el-form-item label="表名称" prop="tableName">
          <el-input v-model="selectFormModel.tableName" placeholder="表名称" style="width: 200px" clearable
                    @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item label="表描述" prop="tableComment">
          <el-input v-model="selectFormModel.tableComment" placeholder="表描述" style="width: 200px" clearable
                    @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
          </el-button>
          <el-button type="warning" icon="el-icon-refresh" size="mini" plain round
                     @click="onRefreshSelectForm">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-download" size="mini" plain @click="batchGenCode"
                 :disabled="dialog.isBatchGenCodeDisabled"
                 v-permission="'tool:gen:code'">
        生成
      </el-button>
      <el-button type="default" icon="el-icon-upload" size="mini" plain @click="importTableClick"
                 v-permission="'tool:gen:list'">
        导入
      </el-button>
      <el-button type="info" icon="el-icon-edit" size="mini" plain @click="editTable"
                 :disabled="dialog.isBatchEditDisabled"
                 v-permission="'tool:gen:edit'">
        编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" size="mini" plain @click="deleteTable"
                 :disabled="dialog.isBatchRemoveDisabled"
                 v-permission="'tool:gen:remove'">
        删除
      </el-button>
    </el-row>
    <data-table ref="dataTable"
                :options="options"
                :operates="operates"
                :api="getGenList"
                :columns="columns"
                :query="selectFormModel"
                @handle-selection-change="handleSelectionChange"
    />

    <el-dialog :title="input.title"
               :visible.sync="input.dialogFormVisible"
               :modal-append-to-body="false"
               :destroy-on-close="false"
               @close="closeDialog"
               width="800px">


      <data-table ref="inputDataTable"
                  :options="inputOptions"
                  :api="getGenDBList"
                  :columns="inputColumns"
                  @handle-selection-change="handleSelectionTable"
      />


      <div slot="footer" class="dialog-footer">
        <el-button @click="input.dialogFormVisible=false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import DataTable from '@/components/DataTable/DataTable.vue';
import {batchGenCode, delTable, genCode, getGenDBList, getGenList, importTable, syncDb} from '@/api/gen';
import {mimeMap, resolveBlob} from '@/utils';


@Component({
  components: {
    DataTable
  }
})
export default class Gen extends Vue {
  private getGenList: any = getGenList;
  private getGenDBList: any = getGenDBList;
  @Ref('dataTable') private dataTable: any;

  @Ref('selectForm') private selectForm: any;

  /*搜索框*/
  selectFormModel: any = {
    tableName: '',
    tableComment: ''
  };
  /*列信息*/
  columns: any = [
    {label: 'ID', prop: 'id'},
    {label: '表名', prop: 'tableName'},
    {label: '描述', prop: 'tableComment', showOverflowTooltip: true},
    {label: '实体', prop: 'className'},
    {label: '创建时间', prop: 'createTime', width: 160, showOverflowTooltip: true},
    {label: '更新时间', prop: 'updateTime', width: 160, showOverflowTooltip: true},
  ];

  // table 的参数
  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
  };
  /*操作栏*/
  operates: any = {
    title: '操作',
    width: 'auto',
    fixed: 'right',
    list: [
      /*{
        label: '预览',
        type: 'default',
        icon: 'el-icon-view',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'tool:gen:code',
        method: (index, row) => {
          this.genCode(index, row);
        }
      },*/ {
        label: '编辑',
        type: 'info',
        icon: 'el-icon-edit',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'tool:gen:code',
        method: (index, row) => {
          this.editTable(index, row);
        }
      }, {
        label: '删除',
        type: 'danger',
        icon: 'el-icon-remove',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'tool:gen:code',
        method: (index, row) => {
          this.deleteTable(index, row);
        }
      }, {
        label: '同步',
        type: 'warning',
        icon: 'el-icon-refresh',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'tool:gen:code',
        method: (index, row) => {
          this.syncTable(index, row);
        }
      }, {
        label: '生成代码',
        type: 'primary',
        icon: 'el-icon-download',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'tool:gen:code',
        method: (index, row) => {
          this.genCode(index, row);
        }
      },
    ]
  };

  dialog: any = {
    isBatchGenCodeDisabled: true,
    isBatchRemoveDisabled: true,
    isBatchEditDisabled: true,
    formData: []
  };

  input: any = {
    dialogFormVisible: false,
    title: '导入表'
  };

  // table 的参数
  inputOptions: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
    rowClassName: "dialogTableRow"
  };
  /*列信息*/
  inputColumns: any = [
    {label: '表名', prop: 'tableName', showOverflowTooltip: true},
    {label: '描述', prop: 'tableComment', showOverflowTooltip: true},
    {label: '创建时间', prop: 'createTime', width: 160, showOverflowTooltip: true},
    {label: '更新时间', prop: 'updateTime', width: 160, showOverflowTooltip: true},
  ];
  /*导入表 选中的表信息*/
  selectTable: any = []

  importTableClick() {
    this.input.dialogFormVisible = true;

    this.$nextTick(() => {
      (this.$refs.inputDataTable as DataTable).refresh();
    })
  }

  /*关闭对话框*/
  closeDialog() {
    this.input.dialogFormVisible = false;
  }

  submitForm(): void {
    console.log("submitForm");
    let tableNames = this.selectTable.map(table => table.tableName);
    importTable({tables: tableNames}).then((res: any) => {
      this.$message.success(res.msg);
      this.dataTable.refresh();
      this.input.dialogFormVisible = false;
      console.log(res)
    }).catch(err => console.log(err))
  }

  /*选中导入表名称事件*/
  handleSelectionTable(val): void {
    console.log(val);
    this.selectTable = val;
  }

  /*选中事件*/
  handleSelectionChange(val): void {
    if (val) {
      this.dialog.isBatchGenCodeDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
    }
    this.dialog.formData = val;
  }

  /*生成代码*/
  batchGenCode(index: number, row: any): void {
    this.$confirm('确定要生成选中表的代码吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const tableNames: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        tableNames[index] = item.tableName;
      });
      return batchGenCode({'tables': tableNames.join(",")});
    }).then((response: any) => {
      resolveBlob(response, mimeMap.zip);
    }).catch((e) => {
      console.log(e);
    });
  }

  genCode(index: number, row: any): void {
    this.$confirm('确定要生成该表的代码吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return genCode({'tableName': row.tableName});
    }).then((response: any) => {
      resolveBlob(response, mimeMap.zip);
    }).catch((e) => {
      console.log(e);
    });
  }

  /*搜索*/
  onSearch(): void {
    this.dataTable.refresh();
  }

  /*重置*/
  onRefreshSelectForm(): void {
    //恢复搜索默认信息
    this.selectForm.resetFields();
    this.onSearch();
  }

  private deleteTable(index, row) {
    this.$confirm('确定要删除' + row.tableName + '吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return delTable(row);
    }).then((response: any) => {
      this.$message.success(response.msg);
      this.dataTable.refresh();
    }).catch((e) => {
      console.log(e);
    });
  }

  private syncTable(index, row) {
    this.$confirm('确定要同步' + row.tableName + '吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }).then(() => {
      return syncDb(row);
    }).then((response: any) => {
      this.$message.success(response.msg);
      this.dataTable.refresh();
    }).catch((e) => {
      console.log(e);
    });
  }

  private editTable(index, row) {
    const tableId = row ? row.id : this.dialog.formData.length > 0 ? this.dialog.formData[0].id : null;
    if (tableId) {
      this.$router.push('/tool/gen/edit/' + tableId).catch((e) => {
        console.log(e);
      });
    }
  }
}
</script>

<style scoped lang="scss">

</style>

